//app.js
App({
    globalData: {
        isIpx: false,
        userInfo: null,
        // rootPath: 'http://192.168.1.5:8083/',
        // rootPath: 'https://cjtest.verygrow.com/',
        rootPath: 'https://bigc.verygrow.com/',
        authId: '',
        authority: '07', //00 超级管理员 01管理员 02交付组组长 03交付组成员 04团长 05副团长 06工程师 07外部人员 09口令访客
        realname: '游客',
        uid: '',
        realpicurl: 'http://static.map8.com/sp/20200927/0_154453540424.jpg', //同事宝头像
        localcityTeam: '', //团队
        screenHeight: Number,
        loginPhone: '',
        // powerPhone: [
        //     '15151801902',
        //     '15252471071',
        //     '18051990010',
        //     '18262331596',
        //     '15077828725',
        //     '18668223899',
        //     '18390688566',
        //     '15051861024',
        //     '18611999116',
        //     '13337704430',
        //     '15751576509',
        //     '18351951218',
        //     '18014711995',
        //     '15077863177',
        //     '18351935808',
        //     '18061283501',
        //     '17715239585',
        //     '19941538330',
        //     '15861831621',
        //     '15255740516',
        //     '15106116900',
        //     '18855057202',
        // ], //权限手机号
        powerPhone: [
            '15151801902',
            '15252471071',
            '13337704430', //盛总
            '18051990010',
            '18262331596',
            '15077828725',
            '18668223899',
            '18390688566',
            '15051861024',
            '18351951218',
            '18611999116', //王总
            '18408231386',
            '15077863177',
            '15751576509',
            '18014711995',
        ], //权限手机号--正式服
        isPowerPhone: false, //是否有权限
        locationLat: Number, //定位经纬度
        locationLng: Number,
        cityLat: Number, //城市经纬度
        cityLng: Number,
        addressTap: '', //定位的城市
        addressBack: '定位中...', //切换的城市
        countryTap: '', //定位的国家
        countryBack: '', //切换的国家
        province: '', //定位的省份
        district: '', //定位的区域，如江宁区、昆山市
        taiwan: [
            '台湾',
            '台北',
            '高雄',
            '台南',
            '台中',
            '南投',
            '基隆',
            '新竹',
            '嘉义',
            '新北',
            '宜兰',
            '新竹县',
            '桃园',
            '苗栗',
            '彰化',
            '嘉义县',
            '云林',
            '屏东',
            '台东',
            '花莲',
            '澎湖',
        ], //匹配台湾城市
        getuserinfoBtn: false, //获取用户信息授权按钮
        wxavatarUrl: '', //微信头像
        openidValue: '',
        expRefresh: false, // 经验首页刷新标志位
        indexExpRefresh: false, // 首页地图点详情刷新标志位
        nqModuleCount: 0, //通告总未读数
        exModuleCount: 0, //经验总未读数
        mineModuleCount: 0, //我的总未读数
    },
    onLaunch: function () {
        var _that = this;
        _that.getPhoneInfo();
        _that.getUserInfo();
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || [];
        logs.unshift(Date.now());
        wx.setStorageSync('logs', logs);
        //初始化云函数
        wx.cloud.init({
            traceUser: true,
            env: 'zts-ed9mp',
        });
        // console.log(_that.getDistance(31.95266, 118.84002, 18.30501, 109.41275))
        // 读取手机号缓存
        console.log(wx.getStorageSync('loginPhone'));
        _that.globalData.loginPhone = wx.getStorageSync('loginPhone');
    },
    getUserInfo: function (cb) {
        var _that = this;
        // 登录
        wx.login({
            success: (res) => {
                let code = res.code;
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                wx.request({
                    url: _that.globalData.rootPath + `code/getOpenidByCode`,
                    method: 'GET',
                    data: {
                        code: code,
                    },
                    success: function (res) {
                        console.log(res);
                        console.log('openid', res.data.openid);
                        _that.globalData.openidValue = res.data.openid;
                        _that.globalData.wxunionid = res.data.unionid;
                        _that.globalData.session_key = res.data.session_key;
                        // 获取用户信息
                        wx.getSetting({
                            success: (res) => {
                                if (res.authSetting['scope.userInfo']) {
                                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                                    _that.globalData.getuserinfoBtn = false;
                                    wx.getUserInfo({
                                        success: (res) => {
                                            _that.globalData.wxavatarUrl =
                                                JSON.parse(
                                                    res.rawData
                                                ).avatarUrl;
                                        },
                                    });
                                }
                            },
                        });
                    },
                });
            },
        });
    },
    getPhoneInfo: function () {
        var _that = this;
        wx.getSystemInfo({
            success: function (res) {
                //model中包含着设备信息
                var model = res.model;
                var system_h = res.windowHeight; //可用窗口高度
                var system_w = res.windowWidth; //可用窗口宽度
                _that.globalData.windowWidth = system_w;
                _that.globalData.windowHeight = system_h;
                if (
                    model.search('iPhone X') != -1 ||
                    model.search('iPhone 11') != -1 ||
                    model.search('iPhone 12') != -1
                ) {
                    _that.globalData.isIpx = true;
                } else {
                    _that.globalData.isIpx = false;
                }
            },
        });
    },
    imgUpload(filePath, returnAll = false) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: 'https://www.map8.com/static/uploadFiles', //仅为示例，非真实的接口地址
                filePath,
                name: 'files',
                formData: {
                    savetype: '03',
                    quality: '',
                },
                comefrom: '05',
                success: (res) => {
                    if (JSON.parse(res.data).urls) {
                        returnAll
                            ? resolve(JSON.parse(res.data))
                            : resolve(JSON.parse(res.data).urls);
                    } else {
                        wx.hideLoading();
                        wx.showToast({
                            title: '无效图片链接',
                            icon: 'none',
                            duration: 2000,
                        });
                        reject(new Error('无有效链接'));
                    }
                },
                fail(err) {
                    wx.hideLoading();
                    wx.showToast({
                        title: '图片上传失败，请检查网络！',
                        icon: 'none',
                        duration: 2000,
                    });
                    reject(err);
                },
            });
        });
    },
    // 获取两点距离
    // getDistance: function (la1, lo1, la2, lo2) {
    getDistance: function (la1, lo1, la2, lo2) {
        let La1 = (la1 * Math.PI) / 180.0;
        let La2 = (la2 * Math.PI) / 180.0;
        let La3 = La1 - La2;
        let Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0;
        let s =
            2 *
            Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(La3 / 2), 2) +
                        Math.cos(La1) *
                            Math.cos(La2) *
                            Math.pow(Math.sin(Lb3 / 2), 2)
                )
            );
        s = s * 6378.137; //地球半径
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(3);
        if (s > 0.5 && s <= 1) {
            s = '<1000m';
        } else if (s <= 0.5) {
            s = '<500m';
        } else {
            // s = Math.round(s)
            s = s + 'km';
        }
        return s;
    },
    // 复制
    copyText: function (content) {
        wx.setClipboardData({
            data: content,
            success: function (res) {
                wx.getClipboardData({
                    success: function (res) {},
                });
            },
        });
    },
    //打电话
    callPhone(phone) {
        wx.makePhoneCall({
            phoneNumber: phone,
        });
    },
    //计算几天前发布
    timeago(time) {
        let dateNow = new Date();
        let monthNow = dateNow.getMonth() + 1;
        monthNow = monthNow > 9 ? monthNow : '0' + monthNow;
        let dayNow =
            dateNow.getDate() > 9 ? dateNow.getDate() : '0' + dateNow.getDate();
        let timeNow = dateNow.getFullYear() + '-' + monthNow + '-' + dayNow;
        let result;
        let str = time; // 日期字符串
        str = str.replace(/-/g, '/'); // 将-替换成/，因为下面这个构造函数只支持/分隔的日期字符串
        let date = new Date(str);
        if (date) {
            let dateTimeStamp = date.getTime();
            let minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
            let hour = minute * 60;
            let day = hour * 24;
            let now = new Date().getTime(); //获取当前时间毫秒
            let diffValue = now - dateTimeStamp; //时间差
            let minC = diffValue / minute; //计算时间差的分，时，天，周，月
            let hourC = diffValue / hour;
            let dayC = diffValue / day;
            if (timeNow == time.slice(0, 10)) {
                if (hourC >= 1 && hourC <= 24) {
                    result = parseInt(hourC) + '小时前';
                } else if (minC >= 1 && minC <= 60) {
                    result = parseInt(minC) + '分钟前';
                } else if (
                    (diffValue >= 0 || diffValue < 0) &&
                    diffValue <= minute
                ) {
                    result = '刚刚';
                }
            } else {
                if (dayC.toFixed(0) <= 1) {
                    result = '昨天';
                } else if (dayC.toFixed(0) > 1 && dayC.toFixed(0) < 7) {
                    result = dayC.toFixed(0) + '天前';
                } else {
                    result = time.slice(0, 10);
                }
            }
        } else {
            result = time;
        }
        return result;
    },
    // 游客不可以发布
    visitorPublish() {
        var _that = this;
        if (_that.globalData.authority == '09') {
            wx.showToast({
                title: '访客不可以录入哦！',
                icon: 'none',
                duration: 2000,
            });
            return true;
        } else {
            return false;
        }
    },
    // 权限判断
    powerIdentity(identity, createAuthId = false) {
        //identity 包括的权限 00--超级管理员 01--管理员 02--交付组组长 03--交付组成员 04--团长  05--副团长 06--工程师 07--外部人员 09--口令访客
        //createAuthId 需要操作本人的时候传--authId
        var _that = this;
        let id = identity.split(',');
        console.log(createAuthId);
        if (
            id.includes(_that.globalData.authority) ||
            createAuthId == _that.globalData.uid
        ) {
            return false;
        } else {
            wx.showToast({
                title: '暂无操作权限',
                icon: 'none',
                duration: 2000,
            });
            return true;
        }
    },
    //管理员审核编辑后审核
    doVerify(id, type) {
        let _that = this;
        let data = {
            authId: _that.globalData.authId,
            id: id,
            type: type,
            delflg: '00',
        };
        wx.request({
            url: _that.globalData.rootPath + `cjMap/doVerify`,
            method: 'GET',
            header: {
                'content-type': 'application/json',
            },
            data: data,
            success: function (res) {
                console.log(res);
                if (res.data.status == 0) {
                    let pages = getCurrentPages();
                    let prevPage = pages[pages.length - 3];
                    console.log(prevPage);
                    if (type == '05') {
                        prevPage.refreshCheckIn();
                    } else if (type == '10') {
                        prevPage.refreshExperience();
                    } else {
                        prevPage.refreshInput();
                    }
                    wx.navigateBack({
                        delta: 2,
                    });
                }
            },
        });
    },
    // 字数限制提示
    numLimitTip(length, num) {
        if (length > num - 1) {
            wx.showToast({
                title: `不能超过${num}个字`,
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 1500,
            });
        }
        return;
    },
});
